package studio.xiaoyun.web.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import studio.xiaoyun.web.HttpResponse;
import studio.xiaoyun.web.RestResult;

/**
 * 封装rest控制器的返回值，用于支持多种媒体类型
 * @author 岳正灵
 * @since 1.0.0
 */
public class WebInterceptor extends HandlerInterceptorAdapter {

	@SuppressWarnings("rawtypes")
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object,
			ModelAndView modelAndView) throws Exception {
		if (modelAndView == null || modelAndView.getModel().isEmpty()) return;
		HttpResponse httpResponse = new HttpResponse();
		httpResponse.setTotal((Long) modelAndView.getModel().get(RestResult.KEY_TOTAL));
		httpResponse.setRows((List) modelAndView.getModel().get(RestResult.KEY_ROWS));
		modelAndView.getModel().clear();
		modelAndView.addObject("response", httpResponse);
	}

}
